<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <!-- <el-form-item label="调出使用公司/部门" prop="outUseOrganizationId">
        <el-tree-select
          v-model="formData.outUseOrganizationId"
          :data="deptList"
          :props="defaultProps"
          check-strictly
          filterable
          class="!w-240px"
          node-key="id"
          placeholder="调出使用公司/部门"
        />
      </el-form-item> -->
      <el-form-item label="调出管理员/申请人员" prop="outMamagerId">
        <el-select filterable v-model="formData.outMamagerId" class="!w-240px" placeholder="调出管理员/申请人员" clearable>
          <el-option
            v-for="(user, index) in userList"
            :label="user.nickname"
            :value="user.id"
            :key="index"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="调入使用公司/部门" prop="inUseOrganizationId">
        <el-tree-select
          v-model="formData.inUseOrganizationId"
          :data="deptList"
          :props="defaultProps"
          check-strictly
          filterable
          class="!w-240px"
          node-key="id"
          placeholder="调入使用公司/部门"
        />
      </el-form-item> -->
      <!-- <el-form-item label="转移前使用人员" prop="outUseUserId">
        <el-input v-model="formData.outUseUserId" placeholder="请输入转移前使用人员" />
      </el-form-item> -->
      <el-form-item label="调入管理员" prop="managerId">
        <el-select filterable v-model="formData.managerId" class="!w-240px" placeholder="调入管理员" clearable>
          <el-option
            v-for="(user, index) in userList"
            :label="user.nickname"
            :value="user.id"
            :key="index"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="使用人员" prop="useUserId">
        <el-select filterable v-model="formData.useUserId" class="!w-240px" placeholder="使用人员" clearable>
          <el-option
            v-for="(user, index) in userList"
            :label="user.nickname"
            :value="user.id"
            :key="index"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="位置" prop="position">
        <el-input v-model="formData.position" placeholder="请输入位置" />
      </el-form-item>
      <el-form-item label="转移说明" prop="content">
        <!-- <Editor v-model="formData.content" height="150px" /> -->
        <el-input v-model="formData.content" placeholder="请输入转移说明" type="textarea" />
      </el-form-item>
      <el-form-item label="附件" prop="attach">
        <UploadFile v-model="formData.attach" class="min-w-80px" />
      </el-form-item>
      <el-form-item label="资产" prop="asset" >
          <el-button type="primary" @click="handleSelectAsset">选择资产</el-button>
          <el-table  :data="checkList" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column label="主键" align="center" prop="id" />
            <!-- <el-table-column label="办理状态" align="center" prop="status" /> -->
            <el-table-column label="资产编号" align="center" prop="assetCode" />
            <!-- <el-table-column label="资产状态" align="center" prop="assetStatus" /> -->
            <el-table-column align="center" label="资产状态" prop="assetStatus" min-width="90">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.eam_zc_status" :value="scope.row.assetStatus" />
              </template>
            </el-table-column>
            <el-table-column label="资产分类" align="center" prop="categoryName" />
            <el-table-column label="资产名称" align="center" prop="name" /> 
            <!-- <el-table-column label="规格型号" align="center" prop="model" />  -->
            <el-table-column label="归属部门" align="center" prop="useOrganizationName" />
            <el-table-column label="详细地址" align="center" prop="positionDetail" />
          </el-table>
         
          <!-- 分页 -->
          <!-- <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          /> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <Dialog :title="dialogTitle2" v-model="dialogVisible2" width="1200">
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键" align="center" prop="id" />
      <!-- <el-table-column label="办理状态" align="center" prop="status" /> -->
      <el-table-column label="资产编号" align="center" prop="assetCode" />
      <!-- <el-table-column label="资产状态" align="center" prop="assetStatus" /> -->
      <el-table-column align="center" label="资产状态" prop="assetStatus" min-width="90">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.eam_zc_status" :value="scope.row.assetStatus" />
        </template>
      </el-table-column>
      <el-table-column label="资产分类" align="center" prop="categoryName" />
      <el-table-column label="资产名称" align="center" prop="name" /> 
      <!-- <el-table-column label="规格型号" align="center" prop="model" />  -->
      <el-table-column label="归属部门" align="center" prop="useOrganizationName" />
      <el-table-column label="详细地址" align="center" prop="positionDetail" />
    </el-table>
    <template #footer>
      <el-button @click="submitForm2" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible2 = false">取 消</el-button>
    </template>
  </Dialog> 
</template>
<script setup lang="ts">
import { AssetTranferApi, AssetTranferVO } from '@/api/eam/assettranfer'
import { defaultProps, handleTree } from '@/utils/tree'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as AssetApi from '@/api/eam/asset'
import * as UserApi from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'

/** 资产转移 表单 */
defineOptions({ name: 'AssetTranferForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const deptList = ref<Tree[]>([]) // 部门树形结构
const userList = ref<UserApi.UserVO[]>([]) // 全量用户清单
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const loading = ref(true) // 列表的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData:any = ref({
  id: undefined,
  outUseOrganizationId: undefined,
  outMamagerId: undefined,
  inUseOrganizationId: undefined,
  outUseUserId: undefined,
  managerId: undefined,
  useUserId: undefined,
  position: undefined,
  content: undefined,
  attach: undefined,
  asset: undefined,
})
const _checkList: any = ref([])
const formRules = reactive({
})
const formRef = ref() // 表单 Ref

const multipleSelection = ref<any[]>([])

const dialogTitle2 = ref('')
const dialogVisible2 = ref(false)

const checkList = ref([])

const handleSelectAsset =() => {
  getList();
  dialogVisible2.value = true;
 
  // checkList.value.forEach(row => {
  //   console.log(row, 'row')
  //         if (multipleSelection.value.includes(row.id)) {
  //           this.$refs.multipleTable.toggleRowSelection(row, true);
  //         }
  //       });
}
const submitForm2 = () => {
  if (multipleSelection.value.length === 0) {
    message.warning('请选择资产')
    return
  }
  console.log(multipleSelection.value, 'multipleSelection.value')
  checkList.value = _checkList.value
  dialogVisible2.value = false
}
const handleSelectionChange = (val: any[]) => {
  let a:any = [];
  let b: any = []
  val.forEach(item=>{
    a.push(item.id)
    b.push(item)
  })
  _checkList.value = b;
  multipleSelection.value = a;
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  deptList.value = handleTree(await DeptApi.getDeptPage({}))
  userList.value = handleTree(await UserApi.getSimpleUserList())
  
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AssetTranferApi.getAssetTranfer(id)
      formData.value = {
        ...formData.value,
        outMamagerId:Number(formData.value.outMamagerId),
        managerId:Number(formData.value.managerId),
        useUserId:Number(formData.value.useUserId),
      }
      
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AssetApi.getAssetPage({
      pageNp:1,
      pageSize:9999,
      managerId: formData.value.outMamagerId
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AssetTranferVO
    if (formType.value === 'create') {
      await AssetTranferApi.createAssetTranfer({...data,asset:multipleSelection.value.join(',')})
      message.success(t('common.createSuccess'))
    } else {
      await AssetTranferApi.updateAssetTranfer({...data,asset:multipleSelection.value.join(',')})
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    outUseOrganizationId: undefined,
    outMamagerId: undefined,
    inUseOrganizationId: undefined,
    outUseUserId: undefined,
    managerId: undefined,
    useUserId: undefined,
    position: undefined,
    content: undefined,
    attach: undefined,
    asset: undefined,
  }
  formRef.value?.resetFields()
}
</script>